package com.gdsz.libbasic.utils.manage

import android.app.Activity
import java.util.concurrent.CopyOnWriteArrayList

class ActivityTaskManager {
    private val ACTIVITY_ARRAY = CopyOnWriteArrayList<Activity>()
    private  val SINGLE_INSTANCE_ACTIVITY_ARRAY = CopyOnWriteArrayList<Activity>()
    companion object{
        private val SINGLETON: Singleton<ActivityTaskManager> =
            object : Singleton<ActivityTaskManager>() {
                override fun create(): ActivityTaskManager {
                    return ActivityTaskManager()
                }
            }
        fun getInstance(): ActivityTaskManager {
            return SINGLETON.get()
        }
    }

    fun put(targetActivity: Activity) {
        var hasActivity = false
        for (activity in ACTIVITY_ARRAY) {
            if (targetActivity === activity) {
                hasActivity = true
                break
            }
        }
        if (!hasActivity) {
            ACTIVITY_ARRAY.add(targetActivity)
        }
    }

    fun remove(targetActivity: Activity) {
        for (activity in ACTIVITY_ARRAY) {
            if (targetActivity === activity) {
                ACTIVITY_ARRAY.remove(targetActivity)
                break
            }
        }
    }

    fun putSingleInstanceActivity(targetActivity: Activity) {
        var hasActivity = false
        for (activity in SINGLE_INSTANCE_ACTIVITY_ARRAY) {
            if (targetActivity === activity) {
                hasActivity = true
                break
            }
        }
        if (!hasActivity) {
            SINGLE_INSTANCE_ACTIVITY_ARRAY.add(targetActivity)
        }
    }

    fun removeSingleInstanceActivity(targetActivity: Activity) {
        for (activity in SINGLE_INSTANCE_ACTIVITY_ARRAY) {
            if (targetActivity === activity) {
                SINGLE_INSTANCE_ACTIVITY_ARRAY.remove(targetActivity)
                break
            }
        }
    }

    fun getSingleInstanceActivityArray(): CopyOnWriteArrayList<Activity> {
        return SINGLE_INSTANCE_ACTIVITY_ARRAY
    }

    fun getTopActivity(): Activity? {
        return if (ACTIVITY_ARRAY.isEmpty()) {
            null
        } else ACTIVITY_ARRAY[0]
    }

    fun getLastActivity(): Activity? {
        return if (ACTIVITY_ARRAY.isEmpty()) {
            null
        } else ACTIVITY_ARRAY[ACTIVITY_ARRAY.size - 1]
    }

    /**
     * 结束所有Activity
     */
    fun killAllActivity() {
        var i = 0
        val size = ACTIVITY_ARRAY.size
        while (i < size) {
            if (null != ACTIVITY_ARRAY[i]) {
                ACTIVITY_ARRAY[i].finish()
            }
            i++
        }
        ACTIVITY_ARRAY.clear()
    }


    fun removeOtherActivity(targetActivity: Activity) {
        for (activity in ACTIVITY_ARRAY) {
            if (targetActivity !== activity) {
                ACTIVITY_ARRAY.remove(activity)
                activity.finish()
            }
        }
    }
}